package com.test13_访问控制权限;

import org.junit.Test;

/**
 * 单例设计模式
 */
public class YootkDemo_02 {

    @Test
    public void test1() {
//        Singleton instanceA = new Singleton();
//        Singleton instanceB = new Singleton();
//        Singleton instanceC = new Singleton();
        Singleton instanceA = Singleton.getInstance();
        Singleton instanceB = Singleton.getInstance();
        Singleton instanceC = Singleton.getInstance();
        System.out.println(instanceA);
        System.out.println(instanceB);
        System.out.println(instanceC);
    }

    @Test
    public void test2() {
        Singleton2 instanceA = Singleton2.getInstance();
        Singleton2 instanceB = Singleton2.getInstance();
        Singleton2 instanceC = Singleton2.getInstance();
        System.out.println(instanceA);
        System.out.println(instanceB);
        System.out.println(instanceC);
    }
}

/**
 * 单例设计模式(饿汉式)
 * 不管是否使用，都在提供好一个实例化对象
 */
class Singleton {
    private static final Singleton INSTANCE = new Singleton();  // 实例化对象

    private Singleton() {   // 构造方法私有化
    }

    public static Singleton getInstance() {     // 获取实例化对象
        return INSTANCE;
    }

    @Override
    public String toString() {
        return "【" + super.toString() + "】沐言优拓：www.yootk.com";
    }
}

/**
 * 单例设计模式(懒汉式)
 * 第一次使用时再实例化，如果不使用则不进行对象实例化
 */
class Singleton2 {
    private static Singleton2 instance;

    private Singleton2() {   // 构造方法私有化
    }

    public static Singleton2 getInstance() {     // 获取实例化对象
        if (instance == null) {
            instance = new Singleton2();
        }
        return instance;
    }

    @Override
    public String toString() {
        return "【" + super.toString() + "】沐言优拓：www.yootk.com";
    }
}
